<template>
  <div class="log">
    <!-- 统计 -->
    <div class="header">
      <van-collapse v-model="activeNames">
        <van-collapse-item title="错误统计" name="1">
          <div
            class="header-item items-center"
            v-for="(item, index) in pageData.errorTypeObjs"
            :key="index"
          >
            <div class="items-center">
              <div style="color: aqua; font-size: 30px">{{ index }}:</div>
              <div class="header-item-info">
                <div class="header-item-info-id">
                  {{ `${item.id} : ${item.info.type}` }}
                </div>
                <div class="header-item-info-title">
                  {{ item.info.message }}
                </div>
              </div>
            </div>

            <div class="header-item-nums" @click.stop="jumpPage(item)">
              {{ item.nums }}
            </div>
          </div>
        </van-collapse-item>
      </van-collapse>
    </div>
    <!-- 菜单 -->
    <div class="menu items-center">
      <div class="items-center">
        <div class="menu-btn" @click="navigateBack">返回</div>
        <div class="menu-btn" @click="pageClick(true)">上一页</div>
        <div class="menu-btn" @click="pageClick(false)">下一页</div>
        <!-- sid -->
        <div class="items-center">
          <div style="font-size: 15px">SID:</div>
          <input
            class="menu-input"
            type="text"
            v-model="pageData.userSid"
            placeholder="请输入用户sid"
          />
        </div>
        <!-- errorId -->
        <div class="items-center">
          <div style="font-size: 15px">errorId:</div>
          <input
            class="menu-input"
            type="text"
            v-model="pageData.errorId"
            placeholder="请输入错误errorId"
          />
        </div>
        <!-- 错误类型选择 -->
        <Dropdown
          :options="pageData.errorTypes"
          placeholder="请选择类型"
          @update:selected="handleSelection"
        ></Dropdown>
        <!-- 日期选择 -->
        <DatePicker v-model="pageData.begin" label="开始时间:" />
        <DatePicker v-model="pageData.end" label="结束时间:" />
      </div>
      <div class="menu-btn" @click="getServeLogRequest">查询</div>
    </div>
    <!-- 内容 -->
    <div class="content">
      <van-collapse v-model="pageData.activeName" accordion>
        <div v-for="(item, index) in pageData.list" :key="item.storeId">
          <van-collapse-item
            style="background-color: #f4f4f4"
            :name="`${item.storeId}${index}`"
          >
            <!-- 一级列表 -->
            <template #title>
              <div
                class="content-title items-center"
                style="justify-content: space-between"
              >
                <div>
                  <span class="content-title-xh"
                    >{{
                      index + (pageData.pageNumber - 1) * pageData.pageSize
                    }}:</span
                  >
                  <span class="content-title-sid">{{
                    item.authInfo.trackerId
                  }}</span>
                  <!-- <span class="content-title-email">{{ item.email }}_</span> -->
                  <!-- <span class="content-title-diviceType">{{
                    item.deviceInfo
                  }}</span> -->
                </div>
                <div class="items-center">
                  <span class="content-title-time">{{ item.time }}</span>
                  <div
                    style="margin-left: 10px"
                    @click.stop="removelogRequest(item)"
                  >
                    ❌删除
                  </div>
                </div>
              </div>
            </template>
            <!-- 二级列表 -->
            <van-collapse v-model="pageData.activeSubName" accordion>
              <div>
                <div class="content-sub-pageurl">
                  <span style="color: red">页面地址</span>:{{ item.data.url }}
                </div>
                <div class="content-sub-errorinfo">
                  <span style="color: red">错误信息</span>:{{
                    item.data.message
                  }}
                </div>
              </div>
              <div v-for="(sub, idx) in item.breadcrumb" :key="sub.id">
                <van-collapse-item :name="idx">
                  <template #title>
                    <div>
                      <div
                        class="content-title items-center"
                        style="justify-content: space-between"
                      >
                        <div>
                          {{
                            `${
                              index + pageData.pageNumber * pageData.pageSize
                            }-${idx}`
                          }}:
                          <span class="content-title-sid">{{ sub.type }}~</span>
                        </div>
                        <div class="content-title-time">{{ sub.time }}</div>
                      </div>
                    </div>
                  </template>
                  <pre class="json" v-html="sub.html"></pre>
                </van-collapse-item>
              </div>
            </van-collapse>
          </van-collapse-item>
        </div>
      </van-collapse>
    </div>
  </div>
</template>
<script setup name="log">
import { getServeLog, removelog } from "../api/log.ts";
import { useDateFormat } from "@vueuse/core";
import { useUserStore } from "~~/store/modules/user";
import { navigateBack } from "@/utils";
import DatePicker from "../../components/log/logDatePicker.vue";
import Dropdown from "../../components/log/selectDropdown.vue";

const userState = useUserStore();
const route = useRoute();
console.log("页面参数:", route.query);

const activeNames = ref(["1"]);
// 是否有权限访问数据
const isPermissions = computed(() => {
  // if (userState.$state.email) {
  //   return (
  //     route.query.who === "zhj" && userState.$state.email.includes("zhj1214")
  //   );
  // }
  return route.query.who === "zhj";
  // return false;
});

// 页面属性
const pageData = reactive({
  errorTypes: [
    { value: "", label: "ALL" },
    { value: "UNKNOWN", label: "UNKNOWN" },
    { value: "UNKNOWN_FUNCTION", label: "UNKNOWN_FUNCTION" },
    { value: "JAVASCRIPT_ERROR", label: "JAVASCRIPT_ERROR" },
    { value: "LOG_ERROR", label: "LOG_ERROR" },
    { value: "HTTP_ERROR", label: "HTTP_ERROR" },
    { value: "VUE_ERROR", label: "VUE_ERROR" },
    { value: "REACT_ERROR", label: "REACT_ERROR" },
    { value: "RESOURCE_ERROR", label: "RESOURCE_ERROR" },
    { value: "PROMISE_ERROR", label: "PROMISE_ERROR" },
    { value: "ROUTE_ERROR", label: "ROUTE_ERROR" },
  ],
  selectErrorType: "",
  activeName: "2",
  activeSubName: "",
  list: [],
  userSid: "",
  message: "",
  begin: "",
  end: "",
  pageSize: 50,
  pageNumber: 1,
  errorTypeObjs: [], // 统计数据
});

/**
 * @description: json数据格式化
 * @param {*} json
 * @return {*} html
 */
const syntaxHighlight = function (json) {
  if (typeof json != "string") {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
  return json.replace(
    /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
    function (match) {
      var cls = "number";
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = "key";
        } else {
          cls = "string";
        }
      } else if (/true|false/.test(match)) {
        cls = "boolean";
      } else if (/null/.test(match)) {
        cls = "null";
      }
      return '<span class="' + cls + '">' + match + "</span>";
    }
  );
};
// 获取日志数据
const getServeLogRequest = () => {
  if (!isPermissions.value) return;
  getServeLog({
    pageSize: pageData.pageSize,
    pageNumber: pageData.pageNumber,
    errorType: pageData.selectErrorType,
    userSid: pageData.userSid,
    errorId: pageData.errorId,
    beginTime: pageData.begin ? new Date(pageData.begin).getTime() : undefined,
    endTime: pageData.end ? new Date(pageData.end).getTime() : undefined,
  }).then((res) => {
    // console.log("获取日志:", res);
    if (res) {
      pageData.list = res.list.map((e) => {
        // 1. 错误信息-格式化
        // if(e.data.stack){
        // e.stackHtml = syntaxHighlight([e.data.stack]);
        // }
        // 2. 行为数据-格式化
        if (e.breadcrumb && e.breadcrumb.length > 0) {
          e.breadcrumb.map((q) => {
            let t = q.time || q.createTime;
            if (t) {
              q.time = useDateFormat(t, "HH:mm:ss").value;
            }

            q.html = syntaxHighlight(q.data);
            return q;
          });
        }
        return e;
      });
      pageData.errorTypeObjs =
        res.statistics.sort((a, b) => {
          return b.nums - a.nums;
        }) || [];
    }
  });
};

onMounted(() => {
  if (isPermissions.value) getServeLogRequest();
});
watch(
  () => isPermissions.value,
  (newVal) => {
    if (newVal) getServeLogRequest();
  }
);
// 页码切换
const pageClick = (issyy) => {
  if (issyy) {
    pageData.pageNumber -= 1;
    if (pageData.pageNumber <= 0) pageData.pageNumber = 1;
  } else {
    pageData.pageNumber += 1;
  }
  getServeLogRequest();
};
// 删除日志
const removelogRequest = (val) => {
  console.log("删除:", val);
  removelog({ errorId: val.data.errorId, dbName: val.dbName }).then((res) => {
    if (res) {
      setTimeout(() => {
        getServeLogRequest();
      }, 1000);
    }
  });
};
// 下拉选择事件
const handleSelection = function (option) {
  // this.selectedOption = option;
  console.log("选择了:", option);
  pageData.selectErrorType = option.value;
};

//
const jumpPage = (val) => {
  if (val.id) {
    navigateI18nTo({
      path: "/log/error-detail",
      query: {
        errorId: val.id,
      },
    });
  }
};
</script>
<style lang="scss" scoped>
.header {
  // padding: 15 * 2px;
  &-title {
    font-size: 22 * 2px;
    font-weight: 600;
    margin-bottom: 10px;
  }
  &-item {
    justify-content: space-between;
    margin-bottom: 10px;
    &-info {
      &-id {
        font-size: 14 * 2px;
      }
      &-title {
        @include multi-line-omit(1);
        font-size: 10 * 2px;
      }
    }
    &-nums {
      color: red;
    }
  }
}
.menu {
  justify-content: space-between;
  padding: 16px;
  &-btn {
    font-size: 15px;
    border: 1px solid #666;
    padding: 10px;
    border-radius: 4px;
    margin-right: 12px;
  }
  &-input {
    font-size: 15px;
    margin-right: 12px;
    padding: 10px;
  }
}
.log {
  position: relative;
  // background-color: #f4f5f7;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
  margin-bottom: constant(safe-area-inset-bottom);
  margin-bottom: env(safe-area-inset-bottom);
  padding-bottom: 33 * 2px;
}
.content {
  &-title {
    font-size: 17px;
    &-xh {
      font-size: 25px;
    }
    &-sid {
      color: #004fee;
    }
    &-diviceType {
      color: #02af17;
    }
    &-email {
      color: #ee00e2;
    }
    &-time {
      color: #ee4b00;
    }
  }
  &-sub {
    &-pageurl {
      font-size: 14px;
    }
    &-errorinfo {
      font-size: 14px;
    }
  }
}
</style>
<style lang="scss">
.json {
  font-size: 11px;
  .pre {
    outline: 1px solid #ccc;
    padding: 5px;
    margin: 5px;
  }
  .string {
    color: green;
  }
  .number {
    color: darkorange;
  }
  .boolean {
    color: blue;
  }
  .null {
    color: magenta;
  }
  .key {
    color: red;
  }
}
</style>
